#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# A little WTF moment brought to you by Toyota
#

import xml.parsers.expat


class Item:
    class InnerItem:
        def __init__(self):
            pass
        # Iga field saab veel name + '_attrs' kui xmlis on attribuute ka
        # ehk item_attrs

    item = None
    title = None
    guid = None
    pubDate = None
    category = None #{}
    link = None #{}
    enclosure = None #{u'url': u'http://www.mininova.org/get/2413821', u'length': u'731572224', u'type': u'application/x-bittorrent'}
    description = None #{}

'''
    # See hack millegipärast kasutab aint yht instansi :S
    innerItem = InnerItem()
    def __init__(self):
        pass
    def __repr__(self):
        return "'%s'" %self.innerItem.title

    def __setattr__(self, name, value):
        setattr(self.innerItem, name, value)

    def __getattr__(self, name):
        # Kui ei ole private attrib ja ei ole sellist, siis tee.
        if not name.startswith('__') and not hasattr(self.innerItem, name):
            setattr(self.innerItem,name, None)
        return getattr(self.innerItem, name)
'''

class XMLParser(object):
    item = None
    items = []
    last_element = None

    def __init__(self):
        self.parser = xml.parsers.expat.ParserCreate()
        self.parser.StartElementHandler = self.start_element
        self.parser.EndElementHandler = self.end_element
        self.parser.CharacterDataHandler = self.char_data

    def start_element(self,name, attrs):
        #print 'Start element: "%s"'% name, attrs
        if name=='item':
            self.item = Item()
        if self.item and hasattr(self.item, name):
            setattr(self.item,name + '_attrs', attrs)
        self.last_element = name

    def end_element(self,name):
        #print 'End element:', name
        if name == 'item': 
            self.items.append(self.item)
            self.item = None

    def char_data(self,data):
        #print 'Character data for %s:' % self.last_element, repr(data)
        if self.item and hasattr(self.item,self.last_element): 
            #print "Title", item.title
            old_data = getattr(self.item, self.last_element)
            if not old_data: old_data = ''
            setattr(self.item, self.last_element, old_data + data)


if __name__=="__main__":
    p = XMLParser()
    f=open('what.rss','r')
    p.parser.Parse( f.read(),1)
    f.close()

    print "Items:",len(p.items)

    print p.items[1].description
    p.items[0].juku = 'What?'
    print "Juku:", p.items[0].juku
